import axios from 'axios'

/**
 * HTTP 请求组件，基于axios
 * Created by yangyao on 2017/7/10.
 */

// 全局基本URL配置
var JzHttp = axios.create({timeout: 15000})
JzHttp.interceptors.request.use(function (config) {
  let cacheConfig = window.sessionStorage.getItem(BASE_CONFIG.cacheKey)
  if (!config.url.startsWith('https://common.jzdoctor.com/base/clientOauth.json') && cacheConfig === null) {
    throw new Error('尚未认证')
  }
  let ak = true
  if (!config.url.startsWith('https://common.jzdoctor.com/base/clientOauth.json')) {
    cacheConfig = JSON.parse(cacheConfig)
    if (!config.url.startsWith('https://') && !config.url.startsWith('http://')) {
      config.url = cacheConfig.baseUrl + config.url
    }
    ak = false
  }
  var url = config.url
  var params = []
  if (url.indexOf('?') !== -1) {
    var arrs = url.split('?')[1].split('&')
    for (var i in arrs) {
      let arr = arrs[i].split('=')
      if (arr.length === 2) {
        params.push({
          name: arr[0],
          value: arr[1]
        })
      }
    }
  }
  if (!ak) {
    url = url.split('?')[0] + '?access_token=' + cacheConfig.access_token
  } else {
    url = url.split('?')[0] + '?rq=' + new Date().getTime()
  }
  for (let i in params) {
    url += ('&' + params[i].name + '=' + params[i].value)
  }
  config.url = url
  console.log('正在发送请求', config)
  // console.log('?access_token=' + cacheConfig.access_token)
  return config
}, function (error) {
  // 对请求错误做些什么
  console.log('请求发生错误', error)
  if (ERROR_FUNC.rqError !== null) {
    ERROR_FUNC.rqError(error)
  }
  return Promise.reject(error)
})
JzHttp.interceptors.response.use(function (resp) {
  console.log('请求结束', resp)
  if (resp.data.statusCode === STATUS_CODE.ACCESS_TOKEN_ERROR) {
    console.log('请求token已失效')
    refreshToken(null)
  }
  return resp
}, function (error) {
  console.log('响应错误', error)
  if (ERROR_FUNC.rpError) {
    ERROR_FUNC.rpError(error)
  }
  return Promise.reject(error)
})

const APP_TYPE = {
  WECHAT_SERVICE: 'WECHAT_SERVICE',
  WECHAT_APP: 'WECHAT_APP',
  WECHAT_SUBSCRIBE: 'WECHAT_SUBSCRIBE',
  WAP: 'WAP',
  APP: 'APP'
}

const BASE_CONFIG = {
  unionid: '',
  mobileNo: '',
  appid: '',
  appType: '',
  oauth: false,
  access_token: 'null',
  cacheKey: 'oauthConfig',
  baseUrl: ''
}

const ERROR_FUNC = {
  rqError: function (error) {
    // TODO 在此实现全局请求错误处理
    console.log('在此实现全局请求错误处理', error)
  },
  rpError: function (error) {
    // TODO 在此实现全局响应错误处理
    console.log('在此实现全局响应错误处理', error)
  }
}

const STATUS_CODE = {
  SUCCESS: 0,
  SYSTEM_ERROR: -1,
  ACCESS_TOKEN_ERROR: 1,
  SERVICE_ERROR: 2,
  MISS_PARAMETER: 3,
  PARAMETER_ERROR: 4,
  REQUEST_METHOD_ERROR: 5,
  NOT_FOUND_RESOURCE: 6
}

function refreshToken (loginSuccess) {
  JzHttp.post('https://common.jzdoctor.com/base/clientOauth.json?appid=' + BASE_CONFIG.appid +
    '&app_type=' + BASE_CONFIG.appType + '&unionid=' + BASE_CONFIG.unionid + '&mobile_no=' + BASE_CONFIG.mobileNo)
  .then(function (resp) {
    console.log('initToken,', resp.data)
    if (resp.data.statusCode === STATUS_CODE.SUCCESS) {
      BASE_CONFIG.oauth = true
      BASE_CONFIG.access_token = resp.data.data.access_token
      console.log('初始化token成功')
      window.sessionStorage.setItem(BASE_CONFIG.cacheKey, JSON.stringify(BASE_CONFIG))
      if (loginSuccess) {
        loginSuccess(resp)
      }
    }
  })
}

function initConfig (props, loginSuccess) {
  let unionid = props.unionid || ''
  let mobileNo = props.mobileNo || ''
  let appid = props.appid || ''
  let appType = props.appType || ''
  BASE_CONFIG.unionid = unionid
  BASE_CONFIG.mobileNo = mobileNo
  BASE_CONFIG.appid = appid
  BASE_CONFIG.appType = appType
  BASE_CONFIG.baseUrl = props.baseUrl || ''
  // 初始化用户token
  if (window.sessionStorage.getItem(BASE_CONFIG.cacheKey) !== null) {
    console.log('session已经存在认证信息，不再重新获取')
    if (loginSuccess) {
      loginSuccess(null)
    }
    return
  }
  refreshToken(loginSuccess)
}

export default {
  http: JzHttp,
  APP_TYPE: APP_TYPE,
  STATUS_CODE: STATUS_CODE,
  init: function (props, loginSuccess) {
    initConfig(props, loginSuccess)
  }
}
